package com.yeyuanqi.web.client;


import com.vdurmont.emoji.EmojiParser;
import com.yeyuanqi.model.ResponseData.ArticleResponseData;
import com.yeyuanqi.model.domain.Comment;
import com.yeyuanqi.service.ICommentService;
import com.yeyuanqi.untils.MyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.parameters.P;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Controller
@RequestMapping("comments")
public class CommentController {
    private static final Logger logger = LoggerFactory.getLogger(CommentController.class);

    @Autowired
    private ICommentService commentServiceImpl;
    //发表评论
    @PostMapping(value = "/publish")
    @ResponseBody
    public ArticleResponseData publishComment(HttpServletRequest request,
                                              @RequestParam Integer aid,@RequestParam String text){
        //去除js脚本
        text = MyUtils.cleanXSS(text);
        text = EmojiParser.parseToAliases(text);
        //注意导入security的user
        User user =(User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //封装评论信息
        Comment comments=new Comment();
        comments.setArticleId(aid);
        comments.setIp(request.getRemoteAddr());
        comments.setCreated(new Date());
        comments.setAuthor(user.getUsername());
        comments.setContent(text);
        try{
            commentServiceImpl.pushComment(comments);
            logger.info("发布成功，文章id："+aid);
            return ArticleResponseData.ok();
        } catch (Exception e){
            logger.info("发布失败，文章id："+aid+"错误描述："+e.getMessage());
            return ArticleResponseData.fail();
        }

    }
}
